<?php

if($uri == "/api/admin/statistics/all") {
    $template_id = isset($_GET['template_id']) ? intval($_GET['template_id']) : 0;
    $time_range = isset($_GET['time_range']) ? $_GET['time_range'] : 'today';

    // 构建时间条件
    switch($time_range) {
        case 'today':
            $time_condition = "DATE(create_time) = CURDATE()";
            $compare_condition = "DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
            break;
        case 'yesterday':
            $time_condition = "DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
            $compare_condition = "DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 2 DAY)";
            break;
        case 'all':
            $time_condition = "1=1";
            $compare_condition = "1=1";
            break;
        default:
            $time_condition = "DATE(create_time) = CURDATE()";
            $compare_condition = "DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
    }

    // 构建模板条件
    $template_condition = $template_id ? "AND template_id = $template_id" : "";

    // 获取统计数据
    $stats = array();

    // 获取任务总数（不包括未使用的）
    $stats['totalTasks'] = $cnSql->total("releases", "$time_condition AND status != 0 $template_condition");
    $previous_tasks = $cnSql->total("releases", "$compare_condition AND status != 0 $template_condition");
    $stats['tasksTrend'] = $previous_tasks ? round(($stats['totalTasks'] - $previous_tasks) / $previous_tasks * 100, 2) : 0;

    // 获取提交数量（状态为已提交审核、审核通过、审核失败的总和）
    $stats['totalSubmissions'] = $cnSql->total("releases", "$time_condition AND status IN (2,3,4) $template_condition");
    $previous_submissions = $cnSql->total("releases", "$compare_condition AND status IN (2,3,4) $template_condition");
    $stats['submissionsTrend'] = $previous_submissions ? round(($stats['totalSubmissions'] - $previous_submissions) / $previous_submissions * 100, 2) : 0;

    // 获取通过率
    $approved = $cnSql->total("releases", "$time_condition AND status = 3 $template_condition");
    $stats['approvalRate'] = $stats['totalSubmissions'] ? round($approved / $stats['totalSubmissions'] * 100, 2) : 0;
    
    $previous_approved = $cnSql->total("releases", "$compare_condition AND status = 3 $template_condition");
    $previous_rate = $previous_submissions ? ($previous_approved / $previous_submissions * 100) : 0;
    $stats['approvalTrend'] = $previous_rate ? round($stats['approvalRate'] - $previous_rate, 2) : 0;

    // 获取活跃用户数（有提交的用户）
    $stats['activeUsers'] = $cnSql->custom("SELECT COUNT(DISTINCT user_id) as count FROM releases WHERE $time_condition AND status IN (2,3,4) $template_condition")[0]['count'];
    $previous_users = $cnSql->custom("SELECT COUNT(DISTINCT user_id) as count FROM releases WHERE $compare_condition AND status IN (2,3,4) $template_condition")[0]['count'];
    $stats['usersTrend'] = $previous_users ? round(($stats['activeUsers'] - $previous_users) / $previous_users * 100, 2) : 0;

    // 获取状态分布
    $status_distribution = $cnSql->custom("
        SELECT 
            SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as processing,
            SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as approved,
            SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) as rejected,
            SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END) as abnormal
        FROM releases 
        WHERE $time_condition $template_condition
    ")[0];
    $stats['statusDistribution'] = $status_distribution;

    // 获取趋势数据（最近7天）
    $trend_data = $cnSql->custom("
        SELECT 
            DATE(create_time) as date,
            COUNT(CASE WHEN status IN (2,3,4) THEN 1 END) as submissions,
            COUNT(CASE WHEN status = 3 THEN 1 END) as approved
        FROM releases
        WHERE create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) $template_condition
        GROUP BY DATE(create_time)
        ORDER BY date
    ");

    $stats['trendData'] = array(
        'dates' => array_column($trend_data, 'date'),
        'submissions' => array_column($trend_data, 'submissions'),
        'approved' => array_column($trend_data, 'approved')
    );

    // 获取详细数据列表（按模板统计）
    $detail_list = $cnSql->custom("
        SELECT 
            t.id as template_id,
            t.name as template_name,
            COUNT(CASE WHEN r.status != 0 THEN 1 END) as total_tasks,
            COUNT(CASE WHEN r.status IN (2,3,4) THEN 1 END) as submissions,
            COUNT(CASE WHEN r.status = 3 THEN 1 END) as approved,
            COUNT(CASE WHEN r.status = 4 THEN 1 END) as rejected,
            COUNT(DISTINCT CASE WHEN r.status IN (2,3,4) THEN r.user_id END) as active_users
        FROM templates t
        LEFT JOIN releases r ON t.id = r.template_id AND $time_condition
        GROUP BY t.id, t.name
        ORDER BY submissions DESC
    ");

    foreach($detail_list as &$detail) {
        $detail['approvalRate'] = $detail['submissions'] ? 
            round($detail['approved'] / $detail['submissions'] * 100, 2) : 0;
    }

    $stats['detailList'] = $detail_list;

    $outJson->data = $stats;
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
} 